package com.otitan.la.forest.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.otitan.la.forest.system.dto.UserRoleDTO;
import com.otitan.la.forest.system.entity.UserRoleEntity;
import com.otitan.la.forest.system.mapper.UserRoleMapper;
import com.otitan.la.forest.system.service.UserRoleService;
import com.otitan.webapp.framework.basepro.exception.code.BaseResponseCode;
import com.otitan.webapp.framework.basepro.model.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRoleEntity> implements UserRoleService {

    @Transactional
    @Override
    public DataResult add(UserRoleDTO dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return DataResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        String userId = dto.getUserId();
        List<String> roleIds = dto.getRoleIds();
        List<UserRoleEntity> list = new ArrayList<>();
        roleIds.forEach(item -> list.add(new UserRoleEntity(item, userId)));
        // 删除 原用户角色关系
        removeRoleAndUser(dto);

        boolean isSuccess = this.saveBatch(list);
        return isSuccess ? DataResult.success() : DataResult.fail(BaseResponseCode.DATA_NOT_EXIST.getMsg());
    }
    private boolean removeRoleAndUser(UserRoleDTO dto) {
        LambdaQueryWrapper<UserRoleEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(UserRoleEntity::getUserId, dto.getUserId())
                .in(UserRoleEntity::getRoleId, dto.getRoleIds());
        return this.remove(queryWrapper);
    }
    @Override
    public DataResult batchDelete(UserRoleDTO dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return DataResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        boolean isSuccess = removeRoleAndUser(dto);
        log.debug("\n>>>>>>>>> 【删除用户角色关系表】 <<<<<<<<<\n操作结果：{}，ids：{}\n>>>>>>>>> ---- <<<<<<<<<", isSuccess, dto);
        return DataResult.success();
    }

}